from flask import Flask, request, jsonify, render_template
import asyncio
import websockets
import subprocess,os
import signal

app = Flask(__name__)
video_server = None
gstreamer_process = None

def start_gstreamer_pipeline():
    global gstreamer_process
    pipeline = "gst-launch-1.0 filesrc location=input.mp4 ! qtdemux! h264parse ! flvmux ! filesink location=/dev/stderr"
    #pipeline="cat input.flv"
    gstreamer_process = subprocess.Popen(pipeline, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)

def stop_gstreamer_pipeline():
    global gstreamer_process
    if gstreamer_process:
        gstreamer_process.terminate()
        gstreamer_process.wait()
        os.killpg(gstreamer_process.pid, signal.SIGTERM) 
        gstreamer_process = None

async def video_stream(websocket, path):
    global gstreamer_process
    while True:
        video_data = gstreamer_process.stderr.read(65536)
        await websocket.send(video_data)
        #print("send data:",video_data)

@app.route('/start_video_stream', methods=['GET'])
def start_video_stream():
    global video_server, gstreamer_process
    if not video_server:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        start_gstreamer_pipeline()
        video_server = websockets.serve(video_stream, "0.0.0.0", 2224)
        loop.run_until_complete(video_server)
        loop.run_forever()

    
    return jsonify({"status": "Video stream started"})

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/stop_video_stream', methods=['GET'])
def stop_video_stream():
    global video_server, gstreamer_process
    stop_gstreamer_pipeline()
    if video_server:
        video_server.close()
        asyncio.get_event_loop().run_until_complete(video_server.wait_closed())
        video_server = None 
    
    return jsonify({"status": "Video stream stopped"})

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=2223)

